//
//  MainTabBar.swift
//  HMWeibo07
//
//  Created by Xwoder on 15/7/27.
//  Copyright © 2015年 Xwoder. All rights reserved.
//

import UIKit

@objc protocol MainTabBarDelegate : NSObjectProtocol {
    optional func mainTabBarDidClickComposeButton(tabBar: MainTabBar)
}

class MainTabBar: UITabBar {
    
    // 加号按钮
    private lazy var composeButton: UIButton = {
        let button = UIButton(type: UIButtonType.Custom)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        return button
        }()

    
    weak var compoaseButtonDelegate: MainTabBarDelegate?
    func composeButtonClick() {
        compoaseButtonDelegate?.mainTabBarDidClickComposeButton!(self)
    }
    

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundImage = UIImage(named: "tabbar_background")
        // 设置tabBar的背景颜色
        self.barTintColor = UIColor.redColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    

    
    // 按钮的数量
    private let buttonCount = 5
    
    override func layoutSubviews() {
        super.layoutSubviews()

        // 每个按钮的宽度
        let buttonW = frame.width / CGFloat(buttonCount)
        
        // 取得tabBar上的所有按钮
        // index值的范围是[1, 4]
        for (index, subView) in subviews.enumerate() {
            if subView is UIControl {
                let button = subView
                if index <= 2 {
                    // 前2个按钮，往左移
                    button.frame = CGRectMake(CGFloat(index - 1) * buttonW, 0, buttonW, bounds.height)
                } else {
                    // 后2个按钮，往右移
                    button.frame = CGRectMake(CGFloat(index) * buttonW, 0, buttonW, bounds.height)
                }
            }
        }
        
        // 添加加号按钮
        addSubview(composeButton)
        composeButton.center = CGPointMake(bounds.width / 2, bounds.height / 2)
    }
    

}
